package com.example.book_subscribe.login.controlle;

import com.example.book_subscribe.common.utils.CommonField;
import com.example.book_subscribe.common.utils.JwtUtils;
import com.example.book_subscribe.common.utils.RedisTokenService;
import com.example.book_subscribe.common.utils.ResponseResult;
import com.example.book_subscribe.login.dto.UserDto;
import com.example.book_subscribe.login.mapper.LoginMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginControlle {
    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;
    @Resource
    private LoginMapper loginMapper;
//    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping("/login")
    public ResponseResult<?> login(@RequestBody UserDto user) {
        String password = user.getPassword();
        String username = user.getUsername();
        boolean count=loginMapper.checkUserExists(username,password);
        if(count){
            return ResponseResult.okResult("登陆成功");
        }else {
            return ResponseResult.errorResult(404,"登陆失败");
        }
    }
    @Autowired
    private RedisTokenService redisTokenService;
    @PostMapping("/GetOpenid")
//    public ResponseResult<?> login(@RequestParam String code) throws Exception {
    public ResponseResult<?> login1(@RequestBody UserDto userDto) throws Exception {
//        HashMap<String, Object> resultMap = new HashMap<>();
        // 构造请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code=" + userDto.getCode() + "&grant_type=authorization_code";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            String body = response.body().string(); // 获得返回的 JSON 字符串
            log.info(body); // 打印整个响应

            // 使用 Jackson 解析 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(body);

            // 获取 session_key
//            String sessionKey = jsonNode.get("session_key").asText();
//            log.info("session_key: " + sessionKey);

            //获取open_id
            String openId = jsonNode.get("openid").asText();
            boolean isTrue=loginMapper.searchOpenid(openId);
            if(!isTrue){
                loginMapper.insertUser(openId,userDto);
            }else {
                loginMapper.updateUser(openId,userDto);
            }
            log.info("openid:"+openId);

            //返回前端openid和sessionKey
//            resultMap.put("openid",openId);
//            resultMap.put("sessionKey",sessionKey);
//            return resultMap;

            // 返回对象
            Map<String, String> result = new HashMap<>();
            //用手机号和openid生成token
            Map<String, Object> map = new HashMap<String,Object>();
            map.put("openid",openId);
            //加密信息，生成token
            String token = JwtUtils.generateToken(map);
            result.put("token",token);
            //将token字符串写入到redis缓存中-->改为在绑定时候存储redis
//            redisTokenService.saveToken(token, CommonField.OUT_TIME_2_MIN);//2分钟过期

//            return ResponseResult.okResult(result);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(404,"请求失败");
    }
}
